import DatePicker from "components/antd-compatible/date-picker";
import { messages } from "share/common";
import React, { Component, PropTypes } from 'react'
import moment from "moment";
import {  Icon, Popover, Spin, Popconfirm, message } from "antd";
import expenseReportService from "containers/expense-report/expense-report.service";
import Condition from "components/condition";
const { If } = Condition;

class EditSlideDocumentFields extends Component {
  constructor(props) {
    super(props);
    this.state = {
      bookDate: null,
      saving: false
    }
  }

  componentWillMount () {
    this.setState({ bookDate: this.context.info.bookDate })
  }

  handleChange = value => {
    this.setState({ bookDate: value });
  };

  onSaveBookDate = () => {
    const { company, user, refreshInfo } = this.props;
    const { info, entityType } = this.context;
    const { bookDate } = this.state;
    let params = {
      "entityOID": entityType === 1002  ? info.expenseReportOID : info.loanBillOID,//单据oid
      "approvalOID": user.userOID,//审核人oid
      "entityType": entityType,//单据类型 报销单1002 借款单 3001
      "bookDateUpdateType": Number(!!(bookDate)), //更新类型 0 默认(取最终审核当前时间) 1 手工输入时间
      "bookDate": bookDate //记账日期
    };
    this.setState({ saving: true });
    expenseReportService.saveBookDate(params, company.companyOID).then(res => {
      this.setState({
        saving: false,
        bookDate: res.data ? res.data.bookDate : null
      });
      refreshInfo();
    }).catch(() => {
      this.setState({ saving: false });
      message.error(messages('common.save.filed')/*保存失败*/);
    })
  };

  onCancel = () => this.setState({ bookDate: this.context.info.bookDate });

  renderBookDate = () => {
    const { info: { bookDateType } } = this.context;
    const { bookDate } = this.state;
    let showValue = null;
    if (bookDate) {
      showValue = moment(bookDate).format('YYYY-MM-DD');
      bookDateType === 1001 && (showValue += `（${messages('common-1.key1263')/*最终审核通过时将基于规则落值*/}）`)
    } else {
      showValue = messages('common-1.key1264')/*最终审核通过日期*/;
    }
    return showValue;
  };

  getBookDateContent = editable => {
    const { bookDate, saving } = this.state;
    return editable ? (
      <Popconfirm
        title={<DatePicker onChange={this.handleChange} value={bookDate ? moment(bookDate) : null}/>}
        onConfirm={this.onSaveBookDate}
        onCancel={this.onCancel}
        getPopupContainer={triggerNode => triggerNode.parentNode}
        okText={messages('common.save')/*保存*/}
        cancelText={messages('common.cancel')/*取消*/}
      >
        {saving ? <Spin wrapperClassName='spin-as-inline'/> : (
          <span>
            {this.renderBookDate()}
            <Icon type="edit" className='book-date default-color-font' style={{marginLeft: 4}}/>
          </span>
        )}
      </Popconfirm>
    ) : (
      <span>
        {this.renderBookDate()}
      </span>
    )
  };

  renderToolTip = () => {
    return (
      <Popover
        getPopupContainer={triggerNode => triggerNode.parentNode}
        content={
          <div style={{ fontSize: 12 }}>
            <div>{messages('common-1.key1265')/*若空，则单据状态变更为审核通过时，优先按设置中规则落值记账日期，未命中规则以单据状态置为【审核通过】的日期作为记账日期*/}; </div>
            <div>{messages('common-1.key1266')/*若有值，则以自定义日期作为记账日期*/}</div>
          </div>
        }
        placement="bottomLeft"
      >
        <Icon type="info-circle-o" style={{marginLeft: 4}} className='font-disabled'/>
      </Popover>
    )
  };

  static contextTypes = {
    info: PropTypes.object,
    isWaitForAudit: PropTypes.bool,
    entityType: PropTypes.number,
    isAuditEditable: PropTypes.bool
  };

  render() {
    const { isAuditEditable, info: { bookDateType } } = this.context;
    const { onClickEdit, showEdit, showBookDate } = this.props;
    return (showBookDate || showEdit) ? (
      <div className={`edit-slide-document-fields ${ bookDateType === 1001 && showEdit ? 'two-line' : ''}`}>
        <If value={showBookDate}>
          <span className={this.classNames({
            'edit-book-date': true,
            'disabled': !isAuditEditable
          })}>
            <Icon type="calendar" className='mg-r-4 font-size-14 calendar' />
            {messages('common-1.key1267')/*记账日期*/}：
            {this.getBookDateContent(isAuditEditable)}
            {this.renderToolTip()}
          </span>
        </If>
        <If value={showEdit}>
          <span
            className={this.classNames({
              'edit-field-btn': true,
              'f-left': !showBookDate,
              'no-float': bookDateType === 1001
            })}
            onClick={onClickEdit}
          >
            <Icon type="edit" className='mg-r-8 font-size-14' />
            {messages('common-1.key1268')/*编辑单据*/}
          </span>
        </If>
      </div>
    ) : <div style={{height: 16}}/>
  }

}

export default EditSlideDocumentFields;
